package com.cssl.fmmall.interceptor;

import com.cssl.fmmall.vo.ResStatus;
import com.cssl.fmmall.vo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//创建拦截器
@Component
public class CheckTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method=request.getMethod();
        if("OPTIONS".equalsIgnoreCase(method)){
            return true;
        }
        String token = request.getHeader("token");

        System.out.println("--------token>>>:"+token);
        if(token==null){
            //提示请先登录
            Result result=new Result(ResStatus.NO,"请先登录",null);
            this.doResponse(response,result);
        }else{
            try {
                //校验token
                JwtParser parser= Jwts.parser();
                parser.setSigningKey("sbsbsbsb");
                //如果token正确（密码正确且在有效期）则正常运行，否则抛出异常
                Jws<Claims> claimsJws = parser.parseClaimsJws(token);
                return true;
            }catch (ExpiredJwtException e){
                Result result=new Result(ResStatus.NO,"登陆过期，请重新登录",null);
                doResponse(response,result);
            }catch (UnsupportedJwtException e){
                Result result=new Result(ResStatus.NO,"token不合法，请自重",null);
                doResponse(response,result);
            }catch (Exception e){
                Result result=new Result(ResStatus.NO,"请重新登录",null);
                doResponse(response,result);
            }
        }
        return false;
    }

    private void doResponse(HttpServletResponse response,Result result)throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String s=new ObjectMapper().writeValueAsString(result);
        out.print(s);
        out.flush();
        out.close();
    }
}
